<template>
  <view class="index-page">
    <view class="main">
      <!-- tabbar -->
      <v-tab :selected="currentTab" :list="tabbarList" @changeTabbar="changeTabbar" />
      <!-- main page -->
      <home-page
        v-if="currentTab.url === '/pages/index/index'"
       :scroll-top="scrollTop"
       :refresh="refresh"
       :tab="currentTab" />
      <category-page
        v-if="currentTab.url === '/pages/category/index'"
        :refresh="refresh"
        :tab="currentTab" />
      <vip-page
        v-if="currentTab.url === '/pages/discount/index'"
        :refresh="refresh"
        :tab="currentTab" />
      <cart-page
        :t="t"
        v-if="currentTab.url === '/pages/cart/index'"
        :refresh="refresh"
        :tab="currentTab" />
      <center-page
        :t="t"
        v-if="currentTab.url === '/pages/center/index'"
        :refresh="refresh"
        :tab="currentTab" />
    </view>
  </view>
</template>

<script>
import Tab from '../../components/tab'
import HomePage from './pages/home'
import CategoryPage from './pages/category'
import VipPage from './pages/vip'
import CartPage from './pages/cart'
import CenterPage from './pages/center'

import base64 from '../../util/base64'
import HomeModel from '../../api/home'
import ProductModel from '../../api/product'
const homeModel = new HomeModel()
const productModel = new ProductModel()

import { mapState } from 'vuex'
import { saveReferrer } from '../../util/util'

export default {
  components: {
    'v-tab': Tab,
    HomePage,
    CategoryPage,
    VipPage,
    CartPage,
    CenterPage
  },
  computed: {
    // 处理跳转
    ...mapState({
      myUrl: state => state.Url.url
    })
  },
  watch: {
    // 监听跳转
    myUrl: {
      deep: true,
      handler(v) {
        if (v && v.indexOf('?type=') !== -1) {
          const type = +(v.split('=')[1])
          if (type === 4) {
            console.log(this.$store.getters['Url/url'])
          }
          this.changeTabbar(this.tabbarList[type])
          this.$store.dispatch('Url/set_url', '')
        }
      }
    }
  },
  data() {
    return {
      // 当前tabbar索引
      currentTab: {},
      // tabbar列表
      tabbarList: [],
      // 调试使用
      currentIndex: 0,
      // 页面滚动
      scrollTop: 0,
      // 是否刷新
      // refresh: {
      //   home: false,
      //   category: false,
      //   vip: false,
      //   cart: false,
      //   center: false,
      // },
      // 存时间
      refresh: 0,
      t: 0
    }
  },
  methods: {
    // 切换tabbar
    changeTabbar(tab) {
      this.currentTab = tab
      // 刷新时使用
      // const index = this.tabbarList.findIndex(x => x.id === tab.id)
      // this.currentIndex = index
    },
    // 获取tabbar列表
    getTabbar() {
      // const cache = this.$store.getters['Page/tabbar']
      // if (!cache) {
      //   homeModel.getTabbar().then(response => {
      //     let { data } = response
      //     data = base64.parse(data)
      //     this.$store.dispatch('Page/set_tabbar', data.list).then(() => {
      //       this.tabbarList = data.list
      //       this._defaultSelected()
      //     })
      //   })
      // } else {
      //   this.tabbarList = cache
      //   this._defaultSelected()
      // }
      // 缓存还是有问题, 这里不使用缓存
      // homeModel.getTabbar().then(response => {
      //   let { data } = response
      //   data = base64.parse(data)
      //   this.tabbarList = data.list
      //   this._defaultSelected()
      // })
      // 这里只使用VUEX缓存, 刷新就有更新
      const cache = this.$store.getters['Uni/tabbar']
      if (!cache) {
        homeModel.getTabbar().then(response => {
          let { data } = response
          data = base64.parse(data)
          this.$store.dispatch('Uni/set_tabbar', data).then(() => {
            this.tabbarList = data.list
            this._defaultSelected()
          })
        })
      } else {
        this.tabbarList = cache.list
        this._defaultSelected()
      }
    },
    // 默认选择
    _defaultSelected() {
      if (this.tabbarList.length > 0) {
        this.currentTab = this.tabbarList[0]
        if (this.currentIndex > 0 && this.tabbarList.length > this.currentIndex) {
          this.currentTab = this.tabbarList[this.currentIndex]
        }
      }
      // console.log('tabbar', this.tabbarList.length)
    },
  },
  onLoad(options) {
    // 方便开发使用
    // 用于在H5中调试
    if (+options.type > 0) {
      // this.currentTab = this.tabbarList[+options.type]
      this.currentIndex = +options.type
    }
    // 分享
    /*#ifdef MP-WEIXIN*/
    // 微信小程序端执行的逻辑
    uni.showShareMenu({
      menus: ['shareAppMessage', 'shareTimeline'],
    })
    /*#endif*/

    // 保存推荐人
    saveReferrer(options)
  },
  onShow() {
    this.t = new Date().getTime()
    // 隐藏tabbar
    // 只有APP中需要隐藏
    // 因为已经custom了
    try {
      // #ifdef APP-PLUS
      uni.hideTabBar()
      // #endif
    } catch (e) {
    }
    // tabbar
    if (this.tabbarList.length === 0) {
      this.getTabbar()
    }
  },
  onShareAppMessage(res) {
    return {
      // title: this.home && this.home.app_name || '分享',
      path: '/pages/index/index?id='+this.id+'&scene=' +
          (this.$store.getters['User/info'] ? this.$store.getters['User/info'].id : 0),
      // 这里还可以定义图片
      // imageUrl: '',
    }
  },
  // 页面滚动
  onPageScroll(e) {
    // 用来处理首页导航栏
    this.scrollTop = e.scrollTop
    // console.log(this.scrollTop)
  },
  // 下拉刷新
  // 已经关闭了, 因为影响到分类的菜单下拉
  onPullDownRefresh() {
    // console.log(this.currentIndex)
    // console.log(this.currentTab)
    this.refresh = new Date().getTime()
    // uni.showToast({
    //   icon: 'none',
    //   title: '刷新完成',
    //   duration: 200
    // })
    // 模拟加载完成
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 300)
  },
  onHide() {
    // 解决跳转重新加载数据问题
    // console.log('hide ')
    this.t = new Date().getTime()
    // console.log(this.t)
  }
}
</script>

<style lang="scss" scoped>
.index-page {
  /* 背景图片渐变色要和这里对应 */
  //background: #f5f5f5;
  background: $page_bg_color;
  .main {
    padding-bottom: 120rpx;
    min-height: calc(100vh - 120rpx);
  }
}
</style>
